package com.egoo.ticket.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.WorkOrderTriggerInfoDao;
import com.egoo.ticket.server.pojo.dto.WorkOrderTriggerInfoDto;
import com.egoo.ticket.server.pojo.entity.FilterFirst;
import com.egoo.ticket.server.pojo.entity.WorkOrderTriggerInfo;
import com.egoo.ticket.server.pojo.vo.ConditionVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTriggerInfoVo;
import com.egoo.ticket.server.service.FilterFirstService;
import com.egoo.ticket.server.service.WorkOrderTriggerInfoService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author：victor_tang
 * @Date ：2020/1/6
 * @Description：工单触发器信息管理控制器
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/workOrderTriggerInfo", produces = "application" +
		"/json")
@Api(value = "工单触发器信息管理",tags = "工单触发器信息管理",description = "工单触发器信息管理")
public class WorkOrderTriggerInfoController {

	@Autowired
	private WorkOrderTriggerInfoService workOrderTriggerInfoService;
	@Autowired
	private FilterFirstService filterFirstService;
	@Autowired
	private WorkOrderTriggerInfoDao workOrderTriggerInfoDao;



	@ApiOperation(value = "获取工单触发器列表", notes = "获取工单触发器列表")
	@RequestMapping(method = RequestMethod.POST, value = "/getTriggerList")
	public DbResponse getTriggerList(@ApiParam(value = "workOrderTriggerInfoDto")
									 @RequestBody WorkOrderTriggerInfoDto workOrderTriggerInfoDto,
									 HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (workOrderTriggerInfoDto == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "page和pageSize为必传参数！");
		}
		if (workOrderTriggerInfoDto.getPage() == null || workOrderTriggerInfoDto.getPageSize() == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "page和pageSize为必传参数！");
		}
		workOrderTriggerInfoDto.setTenantId(tenantId);
		try {
			// 查询触发器列表
			return workOrderTriggerInfoService.getListBycondition(workOrderTriggerInfoDto);

		} catch (Exception e) {
			log.error("触发器列表查询异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "触发器列表查询异常：" + e);
		}
	}

	@ApiOperation(value = "新增工单触发器", notes = "新增工单触发器")
	@RequestMapping(method = RequestMethod.POST, value = "/addSave")
	public DbResponse addSave(@ApiParam(value = "workOrderTriggerInfo")
									 @RequestBody WorkOrderTriggerInfo workOrderTriggerInfo,
							  HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderTriggerInfo.setTenantId(tenantId);
		String workOrderTypeId = workOrderTriggerInfo.getWorkOrderTypeId();
		String triggerName = workOrderTriggerInfo.getTriggerName();
		if (StringUtils.isEmpty(workOrderTriggerInfo.getTriggerName())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "触发器名称不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfo.getWorkOrderTypeId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单类型id不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfo.getCreateUserId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "创建人id不能为空！");
		}
		WorkOrderTriggerInfoVo workOrderTriggerInfoVo = workOrderTriggerInfoDao.selectByNameAndTypeId(triggerName, workOrderTypeId);
		if(!Objects.isNull(workOrderTriggerInfoVo)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该触发器已存在");
		}
		DbResponse dbResponse = checkPramas(workOrderTriggerInfo);
		if (dbResponse!=null) {
			return dbResponse;
		}


		try {
			// 新增触发器
			return workOrderTriggerInfoService.addSave(workOrderTriggerInfo);

		} catch (Exception e) {
			log.error("新增触发器异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "新增触发器：" + e);
		}
	}


	@ApiOperation(value = "获取工单触发器详情", notes = "获取工单触发器详情")
	@RequestMapping(method = RequestMethod.GET, value = "/getDetailById")
	public DbResponse getDetailById(@ApiParam(value = "id", required = true)
									@RequestParam(name = "id") String id) {
		if (StringUtils.isEmpty(id)) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "请传入触发器id");
		}
		try {

			return workOrderTriggerInfoService.getDetailById(id);

		} catch (Exception e) {
			log.error("触发器详情查询异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"触发器详情查询异常：" + e);
		}

	}

	@ApiOperation(value = "获取工单触发器执行动作类型一级下拉数据", notes = "获取工单触发器执行动作类型一级下拉数据")
	@RequestMapping(method = RequestMethod.GET, value ="/getTriggerActionTypeFirstLists")
	public DbResponse getTriggerActionTypeFirstList(@ApiParam(value ="triggerTypeCode", required = true)
														@RequestParam(name = "triggerTypeCode") String triggerTypeCode,
													HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (StringUtils.isEmpty(triggerTypeCode)) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
					"触发器类型编码不能为空");
		}
		try {
			return workOrderTriggerInfoService.getTriggerActionTypeFirstList(triggerTypeCode,tenantId);

		} catch (Exception e) {
			log.error("获取工单触发器执行动作类型一级下拉数据：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"获取工单触发器执行动作类型一级下拉数据：" + e);
		}

	}
	@ApiOperation(value = "获取工单触发器执行动作类型二级下拉数据", notes = "获取工单触发器执行动作类型二级下拉数据")
	@RequestMapping(method = RequestMethod.GET, value =
			"/getTriggerActionTypeSecondList/{triggerTypeCode}")
	public DbResponse getTriggerActionTypeSecondList(@ApiParam(value =
			"triggerTypeCode", required = true) @PathVariable(name = "triggerTypeCode") String triggerTypeCode,
													 HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (StringUtils.isEmpty(triggerTypeCode)) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
					"触发器类型编码不能为空");
		}
		try {
			return workOrderTriggerInfoService.getTriggerActionTypeSecondList(triggerTypeCode,tenantId);

		} catch (Exception e) {
			log.error("获取工单触发器执行动作类型二级下拉数据：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"获取工单触发器执行动作类型二级下拉数据：" + e);
		}

	}
	@ApiOperation(value = "根据工单类型id获取该类型下的所有模板字段信息", notes =
			"根据工单类型id获取该类型下的所有模板字段信息")
	@RequestMapping(method = RequestMethod.GET, value ="/getWorkTypeAllFiledInfoByWorkOrderTypeId")
	public DbResponse getWorkTypeAllFiledInfoByWorkTypeId(@ApiParam(value ="workOrderTypeId", required = true) @RequestParam(name =
			"workOrderTypeId") String workOrderTypeId) {
		if (StringUtils.isEmpty(workOrderTypeId)) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"工单类型id不能为空");
		}
		try {
			return workOrderTriggerInfoService.getWorkTypeAllFiledInfoByWorkTypeId(workOrderTypeId);

		} catch (Exception e) {
			log.error("根据工单类型id获取该类型下的所有模板字段信息异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"根据工单类型id获取该类型下的所有模板字段信息异常：" + e);
		}

	}
	@ApiOperation(value = "修改工单触发器", notes = "修改工单触发器")
	@RequestMapping(method = RequestMethod.POST, value = "/upadteById")
	public DbResponse upadteById(@ApiParam(value = "workOrderTriggerInfo")
							  @RequestBody WorkOrderTriggerInfo workOrderTriggerInfo) {
		String triggerName = workOrderTriggerInfo.getTriggerName();
		String workOrderTypeId = workOrderTriggerInfo.getWorkOrderTypeId();
		String id = workOrderTriggerInfo.getId();
		if (StringUtils.isEmpty(workOrderTriggerInfo.getId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "触发器id不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfo.getUpdateUserId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "修改人id不能为空！");
		}
		WorkOrderTriggerInfoVo workOrderTriggerInfoVo = workOrderTriggerInfoDao.selectByNameAndTypeId(triggerName, workOrderTypeId);
		if(!Objects.isNull(workOrderTriggerInfoVo)&& !workOrderTriggerInfoVo.getId().equals(id)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该触发器名称已存在,更换后重试");
		}
		DbResponse dbResponse = checkPramas(workOrderTriggerInfo);
		if (dbResponse!=null) {
			return dbResponse;
		}

		try {
			// 修改触发器
			return workOrderTriggerInfoService.updateById(workOrderTriggerInfo);

		} catch (Exception e) {
			log.error("修改触发器异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "修改触发器：" + e);
		}
	}
	/**
	 * TODO 检验触发器新增修改公共参数
	 * @author: victor_tang
	 * @createtime: 2020/1/15 18:14
	 * @param workOrderTriggerInfo 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	private DbResponse checkPramas(WorkOrderTriggerInfo workOrderTriggerInfo){
		JSONObject triggerCondition = workOrderTriggerInfo.getTriggerCondition();
		if (triggerCondition==null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"触发器条件不能为空！");
		}
		JSONObject triggerAction = workOrderTriggerInfo.getTriggerAction();
		if (triggerAction==null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"触发器执行动作不能为空！");
		}
		// 校验满足所有条件数据
		JSONArray allConditionsTableData =triggerCondition.getJSONArray(
				"allConditionsTableData");
		if (allConditionsTableData!=null&&allConditionsTableData.size()>0) {
			List<ConditionVo> allConditionsTableDataList =
					JSONObject.parseArray(allConditionsTableData.toJSONString(), ConditionVo.class);

			DbResponse dbResponse = checkTriggerCondition(allConditionsTableDataList);
			if (dbResponse!=null) {
				return 	dbResponse;
			}
		}
		// 校验满足任意条件数据
		JSONArray randomConditionsTableData = triggerCondition.getJSONArray("randomConditionsTableData");
		if (randomConditionsTableData!=null&&randomConditionsTableData.size()>0) {
			List<ConditionVo> randomConditionsTableDataList =
					JSONObject.parseArray(randomConditionsTableData.toJSONString(), ConditionVo.class);

			DbResponse dbResponse = checkTriggerCondition(randomConditionsTableDataList);
			if (dbResponse!=null) {
				return 	dbResponse;
			}
		}

		return null;
	}

	/**
	 * TODO 校验触发器条件参数
	 * @author: victor_tang
	 * @createtime: 2020/1/15 18:00
	 * @param conditionList 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	private DbResponse checkTriggerCondition(List<ConditionVo> conditionList){
		for (int i = 0; i < conditionList.size(); i++) {
			Integer firstId = conditionList.get(i).getFirstId();
			Integer secondId = conditionList.get(i).getSecondDataId();
			String typeId = conditionList.get(i).getTypeId();
			Object value = conditionList.get(i).getValue();
			if (null == firstId || null == secondId || null == value) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,"筛选条件填写不完整，请补充完整");
			} else {
				FilterFirst filterFirst = filterFirstService.selectById(firstId);
				String name = filterFirst.getName();
				if (firstId == 9 || firstId == 10 || firstId == 11) {
					if (null == typeId) {
						return new DbResponse(ResponseConstant.RES_FAIL_CODE,"筛选条件填写不完整，请补充完整");
					}else {
//							if(3 == secondId || 4 == secondId){
//								try {
//									String value1 = (String) value;
//								} catch (Exception e) {
//									dbResponse.setRetCode(StatusCode.RET_ERROR);
//									dbResponse.setMsg(name + "填写的数据格式不正确");
//									return dbResponse;
//								}
//							}else {
////								List value2 = (List) value;
//								try {
//									List value2 = (List) value;
//								} catch (Exception e) {
//									dbResponse.setRetCode(StatusCode.RET_ERROR);
//									dbResponse.setMsg(name + "填写的数据格式不正确");
//									return dbResponse;
//								}
//							}
					}

				}
				if (firstId == 14) {
					try {
						Integer.parseInt(value.toString());
//						if (secondId == 1 || secondId == 2) {
//							Integer.parseInt(value.toString());
//						} else {
//							List valueList = (List) value;
//							for (int j = 0; j < valueList.size(); j++) {
//								Integer.parseInt(valueList.get(j).toString());
//							}
//						}
					} catch (Exception e) {
						return new DbResponse(ResponseConstant.RES_FAIL_CODE,name + "只能填入整数，否则无法解析");
					}
				}
				if (firstId == 15 || firstId == 16) {
					try {
						if (secondId == 1 || secondId == 2) {
							Double.parseDouble(value.toString());
						} else {
							List valueList = (List) value;
							for (int j = 0; j < valueList.size(); j++) {
								Double.parseDouble(valueList.get(j).toString());
							}
						}
					} catch (Exception e) {
						return new DbResponse(ResponseConstant.RES_FAIL_CODE,name + "只能填入整数，否则无法解析");
					}
				}
			}

//				if (firstId == 14) {
//					try {
//						Integer.parseInt(value.toString());
////						if (secondId == 1 || secondId == 2) {
////							Integer.parseInt(value.toString());
////						} else {
////							List valueList = (List) value;
////							for (int j = 0; j < valueList.size(); j++) {
////								Integer.parseInt(valueList.get(j).toString());
////							}
////						}
//					} catch (Exception e) {
//						dbResponse.setRetCode(StatusCode.RET_ERROR);
//						dbResponse.setMsg(name + "只能填入整数，否则无法解析");
//						return dbResponse;
//					}
//				}
//				if (firstId == 15 || firstId == 16) {
//					try {
//						if (secondId == 1 || secondId == 2) {
//							Double.parseDouble(value.toString());
//						} else {
//							List valueList = (List) value;
//							for (int j = 0; j < valueList.size(); j++) {
//								Double.parseDouble(valueList.get(j).toString());
//							}
//						}
//					} catch (Exception e) {
//						dbResponse.setRetCode(StatusCode.RET_ERROR);
//						dbResponse.setMsg(name + "只能填入数字，否则无法解析");
//						return dbResponse;
//					}
//				}
		}
		return null;
	}
	@ApiOperation(value = "批量修改工单触发器状态", notes = "批量修改工单触发器状态")
	@RequestMapping(method = RequestMethod.POST, value = "/batchUpdateStatus")
	public DbResponse batchUpdateStatus(@ApiParam(value = "workOrderTriggerInfo")
								 @RequestBody WorkOrderTriggerInfoDto workOrderTriggerInfoDto) {

		if (workOrderTriggerInfoDto.getIds()==null || workOrderTriggerInfoDto.getIds().size()==0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "触发器id不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfoDto.getStatus())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "状态不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfoDto.getUpdateUserId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "修改人id不能为空！");
		}

		Map<String, Object> updateMap = new HashMap<>(8);
		updateMap.put("status",workOrderTriggerInfoDto.getStatus());
		updateMap.put("ids",workOrderTriggerInfoDto.getIds());
		updateMap.put("updateUserId",workOrderTriggerInfoDto.getUpdateUserId());

		try {
			// 修改触发器状态
			return workOrderTriggerInfoService.batchUpdate(updateMap);

		} catch (Exception e) {
			log.error("修改工单触发器状态异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"修改工单触发器状态异常：" + e);
		}
	}
	@ApiOperation(value = "批量删除工单触发器", notes = "批量删除工单触发器")
	@RequestMapping(method = RequestMethod.POST, value = "/batchDelete")
	public DbResponse batchDelete(@ApiParam(value = "workOrderTriggerInfo")
								  @RequestBody WorkOrderTriggerInfoDto workOrderTriggerInfoDto) {

		if (workOrderTriggerInfoDto.getIds()==null || workOrderTriggerInfoDto.getIds().size()==0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "触发器id不能为空！");
		}
		if (StringUtils.isEmpty(workOrderTriggerInfoDto.getUpdateUserId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "删除人id不能为空！");
		}
		Map<String, Object> map = new HashMap<>(2);
		map.put("ids",workOrderTriggerInfoDto.getIds());
		try {
			// 删除触发器
			workOrderTriggerInfoService.deleteByConditon(map);
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.DEL_SUCCESS_MSG);

		} catch (Exception e) {
			log.error("删除工单触发器异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"删除工单触发器异常：" + e);
		}
	}

}
